package encode;

import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

public class SHA1Test {

    private final static MessageDigest messageDigest;

    private final static String secretKey = "";

    static {
        try {
            messageDigest = MessageDigest.getInstance("SHA");
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException("MessageDigest SHA is not found");
        }
    }

    public static void tokenLogin(String encodeToken) {
        String decodeToken  = new String(Base64.getDecoder().decode(encodeToken));
        String[] infos = decodeToken.split("%");
        String userName = infos[0];
        String createTime = infos[1];
        String expireTime = infos[2];
        String sign = infos[3];
        //签名校验
        String verifyKey = userName + "%" + createTime + "%" + expireTime + "%" + secretKey;
        String verifySign = Hex.encodeHexString(messageDigest.digest(verifyKey.getBytes()));
        if (!verifySign.equals(sign)) {
            System.out.println("secretKey is error");
        }
        System.out.println(userName);

    }


    private static String genToken() {
        String username = "";
        String createTime = "1528254783";
        String expireTime = "1528254813";
        String key = username + "%" + createTime + "%" + expireTime + "%" + secretKey;
        String sign = Hex.encodeHexString(messageDigest.digest(key.getBytes()));
        String all = username + "%" + createTime + "%" + expireTime + "%" + sign;
        return new String(Base64.getEncoder().encode(all.getBytes()));

    }

    public static void main(String[] args) {
        String token = genToken();
        System.out.println(token);
        tokenLogin(token);
    }

}
